package com.shushan.setting;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.Constants;
import com.shushan.base.NavigationLoseActivity;
import com.shushan.db.ChildBookDao;
import com.shushan.home.TabHomeActivity;
import com.shushan.login.bean.ChildBookBean;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.setting.bean.BookBean;
import com.shushan.setting.bean.GradeBookBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.R;
import com.shushan.ui.CustomDialog;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.SharedPreferencesUtils;
import com.shushan.util.ToolUtils;
import com.shushan.versionupdate.utils.MD5Util;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.List;

/**
 * @ClassName: BookSelectActivity
 * @Desciption: 课本选择
 * @author: yichaohua
 * @date: 2018-08-09
 */
public class BookSelectActivity extends NavigationLoseActivity implements View.OnClickListener {

    private static final String TAG = "BookSelectActivity";

    private ImageView chineseImg;
    private ImageView mathImg;
    private ImageView englishImg;
    private ImageView chineseDelImg;
    private ImageView mathDelImg;
    private ImageView englishDelImg;
    private TextView chinesePressTv;
    private TextView mathPressTv;
    private TextView englishPressTv;
    private Button confirmButton;

    private int gradeId = 1;
    private int firstTime = 0;
    private String semester = "UP";
    private boolean isSetGrade = false;
    private GradeBookBean gradeBookBean;
    private BookBean chineseBook;
    private BookBean mathBook;
    private BookBean englishBook;
    private BabyApplication babyApplication = BabyApplication.getInstance();


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.book_select_activity);

        setTitle("课本选择");

        isSetGrade = getIntent().getBooleanExtra("isSetGrade",false);
        gradeId = getIntent().getIntExtra("gradeId",1);
        semester = getIntent().getStringExtra("semester");
        firstTime = getIntent().getIntExtra("firstTime",0);

        initView();

        initData();
    }

    private void initView() {
        chinesePressTv = findViewById(R.id.book_select_chinese_press_tv);
        mathPressTv = findViewById(R.id.book_select_math_press_tv);
        englishPressTv = findViewById(R.id.book_select_english_press_tv);
        chineseImg = findViewById(R.id.book_select_chinese_img);
        chineseImg.setOnClickListener(this);
        mathImg = findViewById(R.id.book_select_math_img);
        mathImg.setOnClickListener(this);
        englishImg = findViewById(R.id.book_select_english_img);
        englishImg.setOnClickListener(this);

        chineseDelImg = findViewById(R.id.book_select_chinese_del_img);
        chineseDelImg.setOnClickListener(this);
        mathDelImg = findViewById(R.id.book_select_math_del_img);
        mathDelImg.setOnClickListener(this);
        englishDelImg = findViewById(R.id.book_select_english_del_img);
        englishDelImg.setOnClickListener(this);
        confirmButton = findViewById(R.id.book_select_confirm_btn);
        confirmButton.setOnClickListener(this);
    }

    @Override
    protected void onLeftBackward() {
        if(isSetGrade){
            onBackAction();
        }else {
            showBackDialog();
        }
    }

    private void initData() {
        showWaitDialog();

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.GET_GRADE_BOOKS);
        urlParse.putValue("grade_id", gradeId)
                .putValue("semester", semester);

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<GradeBookBean>() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(GradeBookBean bookBeans) {
                        gradeBookBean = bookBeans;

                        if(bookBeans != null){
                            List<BookBean> chineseBookList = bookBeans.getChineseBookList();
                            if(!ToolUtils.isListEmpty(chineseBookList)){
                                for (BookBean bookBean : chineseBookList){
                                    if(bookBean.defaultPress == 1){
                                        setBook(bookBean);
                                    }
                                }
                            }

                            List<BookBean> mathBookList = bookBeans.getMathBookList();
                            if(!ToolUtils.isListEmpty(mathBookList)){
                                for (BookBean bookBean : mathBookList){
                                    if(bookBean.defaultPress == 1){
                                        setBook(bookBean);
                                    }
                                }
                            }

                            List<BookBean> englishBookList = bookBeans.getEnglishBookList();
                            if(!ToolUtils.isListEmpty(englishBookList)){
                                for (BookBean bookBean : englishBookList){
                                    if(bookBean.defaultPress == 1){
                                        setBook(bookBean);
                                    }
                                }
                            }
                        }
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.book_select_chinese_img:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getChineseBookList())){
                    showToast("该年级无此科目");
                    return;
                }

                Session.getSession().put("bookList",gradeBookBean.getChineseBookList());
                startActivityForResult(PressSelectActivity.class);
                break;
            case R.id.book_select_math_img:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getMathBookList())){
                    showToast("该年级无此科目");
                    return;
                }

                Session.getSession().put("bookList",gradeBookBean.getMathBookList());
                startActivityForResult(PressSelectActivity.class);
                break;
            case R.id.book_select_english_img:
                if(gradeBookBean == null || ToolUtils.isListEmpty(gradeBookBean.getEnglishBookList())){
                    showToast("该年级无此科目");
                    return;
                }

                Session.getSession().put("bookList",gradeBookBean.getEnglishBookList());
                startActivityForResult(PressSelectActivity.class);
                break;
            case R.id.book_select_chinese_del_img:
                deleteBook(1);
                break;
            case R.id.book_select_math_del_img:
                deleteBook(2);
                break;
            case R.id.book_select_english_del_img:
                deleteBook(3);
                break;
            case R.id.book_select_confirm_btn:
                if(valide()){
                    submitBooks();
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == 100){
            BookBean selectBookBean = (BookBean) Session.getSession().get("selectBookBean");
            setBook(selectBookBean);
        }
    }

    private void setBook(BookBean selectBookBean) {
        if(selectBookBean == null){
            return;
        }

        switch (selectBookBean.subject_id){
            case Constants.SUBJECT_CHINESE_ID:
                chineseDelImg.setVisibility(View.VISIBLE);
                chinesePressTv.setVisibility(View.VISIBLE);
                chinesePressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,chineseImg);
                chineseBook = selectBookBean;
                break;
            case Constants.SUBJECT_MACH_ID:
                mathDelImg.setVisibility(View.VISIBLE);
                mathPressTv.setVisibility(View.VISIBLE);
                mathPressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,mathImg);
                mathBook = selectBookBean;
                break;
            case Constants.SUBJECT_ENGLISH_ID:
                englishDelImg.setVisibility(View.VISIBLE);
                englishPressTv.setVisibility(View.VISIBLE);
                englishPressTv.setText(selectBookBean.press_name);
                ImageUtils.loadImageNoBg(this,selectBookBean.cover,englishImg);
                englishBook = selectBookBean;
                break;
            default:
                break;
        }
    }

    private void deleteBook(int subject) {
        switch (subject){
            case 1:
                chineseDelImg.setVisibility(View.GONE);
                chinesePressTv.setVisibility(View.GONE);
                chineseImg.setImageResource(R.drawable.chinese_book_add_bg);
                chineseBook = null;
                break;
            case 2:
                mathDelImg.setVisibility(View.GONE);
                mathPressTv.setVisibility(View.GONE);
                mathImg.setImageResource(R.drawable.math_book_add_bg);
                mathBook = null;
                break;
            case 3:
                englishDelImg.setVisibility(View.GONE);
                englishPressTv.setVisibility(View.GONE);
                englishImg.setImageResource(R.drawable.english_book_add_bg);
                englishBook = null;
                break;
            default:
                break;
        }
    }

    private boolean valide() {
        if(chineseBook == null && mathBook == null && englishBook == null){
            showToast("请先添加课本");
            return false;
        }
        return true;
    }

    private void submitBooks() {
        showWaitDialog();

        int childId = babyApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.POST_CHILD_BOOKS);
        urlParse.putValue("child_id", childId)
                .putValue("grade_id", gradeId)
                .putValue("semester", semester)
                .putValue("outline_info", getOutline())
                .putValue("sign", MD5Util.MD5LOW(childId + "sszx" + gradeId + semester));

        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(urlParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        if(!isSetGrade){
                            String parentPasswd = SharedPreferencesUtils.getStringDate(Constants.PARENT_PASSWD_SHAREPREFERS_KEY);
                            if(TextUtils.isEmpty(parentPasswd)){
                                Intent intent = new Intent(BookSelectActivity.this,ParentPswSetActivity.class);
                                intent.putExtra("firstTime",firstTime);
                                startActivityAllow(intent);
                            }else {
                                SharedPreferencesUtils.setBooleanDate(Constants.IS_LOGIN_SHAREPREFERS_KEY,true);
                                Intent intent = new Intent(BookSelectActivity.this,TabHomeActivity.class);
                                intent.putExtra("firstTime",firstTime);
                                startActivityAllow(intent);
                            }
                        }

                        setBookDao();

                        onBackAction(400);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setBookDao() {
        ChildBookDao childBookDao = new ChildBookDao(this);
        if(chineseBook != null || mathBook != null || englishBook != null){
            childBookDao.clearTab();
        }

        if(chineseBook != null){
            ChildBookBean childBookBean = new ChildBookBean();
            childBookBean.id = chineseBook.id;
            childBookBean.grade_id = chineseBook.grade_id;
            childBookBean.grade_name = chineseBook.grade_name;
            childBookBean.semester = chineseBook.semester;
            childBookBean.subject_id = chineseBook.subject_id;
            childBookBean.subject_name = chineseBook.subject_name;
            childBookBean.press_id = chineseBook.press_id;
            childBookBean.press_name = chineseBook.press_name;
            childBookBean.cover = chineseBook.cover;

            childBookDao.add(childBookBean);
        }

        if(mathBook != null){
            ChildBookBean childBookBean = new ChildBookBean();
            childBookBean.id = mathBook.id;
            childBookBean.grade_id = mathBook.grade_id;
            childBookBean.grade_name = mathBook.grade_name;
            childBookBean.semester = mathBook.semester;
            childBookBean.subject_id = mathBook.subject_id;
            childBookBean.subject_name = mathBook.subject_name;
            childBookBean.press_id = mathBook.press_id;
            childBookBean.press_name = mathBook.press_name;
            childBookBean.cover = mathBook.cover;

            childBookDao.add(childBookBean);
        }

        if(englishBook != null){
            ChildBookBean childBookBean = new ChildBookBean();
            childBookBean.id = englishBook.id;
            childBookBean.grade_id = englishBook.grade_id;
            childBookBean.grade_name = englishBook.grade_name;
            childBookBean.semester = englishBook.semester;
            childBookBean.subject_id = englishBook.subject_id;
            childBookBean.subject_name = englishBook.subject_name;
            childBookBean.press_id = englishBook.press_id;
            childBookBean.press_name = englishBook.press_name;
            childBookBean.cover = englishBook.cover;

            childBookDao.add(childBookBean);
        }
    }

    private String getOutline() {
        JSONArray jsonArray = new JSONArray();
        if(chineseBook != null){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("id",chineseBook.id);
                jsonObject.put("level",chineseBook.level);
                jsonObject.put("subject_id",chineseBook.subject_id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        if(mathBook != null){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("id",mathBook.id);
                jsonObject.put("level",mathBook.level);
                jsonObject.put("subject_id",mathBook.subject_id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        if(englishBook != null){
            JSONObject jsonObject = new JSONObject();
            try {
                jsonObject.put("id",englishBook.id);
                jsonObject.put("level",englishBook.level);
                jsonObject.put("subject_id",englishBook.subject_id);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            jsonArray.put(jsonObject);
        }

        return jsonArray.toString();
    }

    private void showBackDialog() {
        new CustomDialog.Builder(this)
                .setTitle("温馨提示")
                .setMessage("发现您尚未完成课本设置，退出将导致无法正常练习，是否退出设置？")
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                        onBackAction();
                    }
                })
                .setPositiveButton("返回", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();

                    }
                })
                .create().show();
    }

    @Override
    public void onBackPressed() {
        if(isSetGrade){
            onBackAction();
        }else {
            showBackDialog();
        }
    }
}
